/**
 * @file    inf_airbag.c
 * @author  yhy
 * @brief   气袋模块源文件
 * @version 1.00
 * @date    2025-07-29
 *
 * @copyright Copyright (c) 2025
 *
 */
#include "inf_airbag.h"

/**
 * @brief 初始化气袋
 *
 * @param airbag                气袋对象指针
 * @param inflate_ch            充气阀门通道
 * @param deflate_ch            泄气阀门通道
 * @param max_inflate_time_ms   最大充气时间
 * @param inflate_rate_ms       充气速率
 * @param deflate_rate_ms       泄气速率
 * @return result_e             初始化结果
 */
result_e inf_airbag_init(airbag_t *airbag, solenoid_valve_channel_e inflate_ch,
                         solenoid_valve_channel_e deflate_ch, uint32_t max_inflate_time_ms,
                         uint16_t inflate_rate_ms, uint16_t deflate_rate_ms)
{
    if (!airbag) {
        return RESULT_STATUS_INVALID_PARAM;
    }

    airbag->inflate_valve_ch    = inflate_ch;
    airbag->deflate_valve_ch    = deflate_ch;
    airbag->inflate_time_ms     = 0;
    airbag->max_inflate_time_ms = max_inflate_time_ms;
    airbag->inflate_rate_ms     = inflate_rate_ms;
    airbag->deflate_rate_ms     = deflate_rate_ms;
    airbag->state               = AIRBAG_STATE_KEEP; // 默认保压状态
    airbag->air_pressure        = 0;
    airbag->inflate_blocked     = false;

    return RESULT_STATUS_OK;
}

/**
 * @brief 设置气袋状态
 *
 * @param airbag        气袋对象指针
 * @param state         要设置的气袋状态
 * @return result_e     设置结果, 成功返回RESULT_STATUS_OK, 失败返回其他
 */
result_e inf_airbag_set_state(airbag_t *airbag, airbag_state_e state)
{
    if (!airbag || state >= AIRBAG_STATE_MAX) {
        return RESULT_STATUS_INVALID_PARAM;
    }

    /* 检查当前状态是否与目标状态相同, 相同直接返回成功 */
    if (airbag->state == state) {
        return RESULT_STATUS_OK;
    }

    switch (state) {
    case AIRBAG_STATE_INFLATE:
    case AIRBAG_STATE_EXHAUST:
        inf_solenoid_valve_set_enable(airbag->inflate_valve_ch, true);
        inf_solenoid_valve_set_enable(airbag->deflate_valve_ch, false);
        break;
    case AIRBAG_STATE_DEFLATE:
        inf_solenoid_valve_set_enable(airbag->inflate_valve_ch, false);
        inf_solenoid_valve_set_enable(airbag->deflate_valve_ch, true);
        break;
    case AIRBAG_STATE_KEEP:
        inf_solenoid_valve_set_enable(airbag->inflate_valve_ch, false);
        inf_solenoid_valve_set_enable(airbag->deflate_valve_ch, false);
        break;
    }

    airbag->state = state;

    return RESULT_STATUS_OK;
}

/**
 * @brief 获取指定气袋当前状态
 *
 * @param   airbag           气袋对象指针
 * @return  airbag_state_e   气袋当前状态
 */
airbag_state_e inf_airbag_get_state(const airbag_t *airbag)
{
    if (!airbag) {
        return AIRBAG_STATE_UNKNOWN;
    }

    return airbag->state;
}

/**
 * @brief 获取指定气袋当前压力
 *
 * @param   airbag     气袋对象指针
 * @return  uint16_t   气袋当前压力，单位KPa, 返回0表示当前气袋为NULL
 */
uint16_t inf_airbag_get_air_pressure(const airbag_t *airbag)
{
    if (!airbag) {
        return 0;
    }

    return airbag->air_pressure;
}
